package com.osfw.system.cotroller.manage;

import com.osfw.framework.annotation.Log;
import com.osfw.framework.constants.Constants;
import com.osfw.framework.constants.UserConstants;
import com.osfw.framework.core.controller.BaseController;
import com.osfw.framework.core.domain.RestfulResult;
import com.osfw.framework.core.domain.Ztree;
import com.osfw.framework.enums.BusinessType;
import com.osfw.framework.utils.StringUtils;
import com.osfw.system.entity.manage.SysDept;
import com.osfw.system.entity.manage.SysMenu;
import com.osfw.system.entity.manage.SysRole;
import com.osfw.system.entity.manage.SysUser;
import com.osfw.system.service.manage.ISysDeptService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 部门信息
 */
@Controller
@RequestMapping("/osfw/system/manage/dept")
public class SysDeptController extends BaseController {
    private String prefix = "osfw/system/manage/dept";

    @Autowired
    private ISysDeptService deptService;

    @RequiresPermissions("system:dept:view")
    @GetMapping()
    public String dept() {
        return prefix + "/dept";
    }

    @RequiresPermissions("system:dept:list")
    @PostMapping("/list")
    @ResponseBody
    public List<SysDept> list(SysDept dept) {
        List<SysDept> deptList = deptService.selectDeptList(dept);
        return deptList;
    }

    /**
     * 查询部门管理数据（直属下级部门）
     *
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @RequiresPermissions("system:dept:list")
    @PostMapping("/listImmediateChildren")
    @ResponseBody
    public List<SysDept> listImmediateChildren(SysDept dept) {
        SysUser user = getSysUser();
        List<SysDept> deptList = deptService.selectImmediateChildrenDeptList(dept, user);
        return deptList;
    }

    /**
     * 新增部门
     */
    @GetMapping("/add/{parentId}")
    public String add(@PathVariable("parentId") Long parentId, ModelMap mmap) {
        if (!getSysUser().isAdmin()) {
            parentId = getSysUser().getDeptId();
        }
        SysDept dept = deptService.selectDeptById(parentId);
        if (StringUtils.isNull(dept)) {
            dept = new SysDept();
            dept.setDeptId(0l);
            dept.setDeptName("无");
        }
        mmap.put("sysDept", dept);
        return prefix + "/add";
    }

    /**
     * 新增保存部门
     */
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @RequiresPermissions("system:dept:add")
    @PostMapping("/add")
    @ResponseBody
    public RestfulResult addSave(@Validated SysDept dept) {
        if (Constants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        return toAjax(deptService.insertDept(dept));
    }

    /**
     * 修改部门
     */
    @RequiresPermissions("system:dept:edit")
    @GetMapping("/edit/{deptId}")
    public String edit(@PathVariable("deptId") Long deptId, ModelMap mmap) {
        deptService.checkDeptDataScope(deptId);
        SysDept dept = deptService.selectDeptById(deptId);
        if (StringUtils.isEmpty(dept.getParentName()) && 0l == dept.getParentId().longValue()) {
            dept.setParentName("无");
        }
        mmap.put("sysDept", dept);
        return prefix + "/edit";
    }

    /**
     * 修改保存部门
     */
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("system:dept:edit")
    @PostMapping("/edit")
    @ResponseBody
    public RestfulResult editSave(@Validated SysDept dept) {
        Long deptId = dept.getDeptId();
        deptService.checkDeptDataScope(deptId);
        if (Constants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        } else if (dept.getParentId().equals(deptId)) {
            return error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus())
                && deptService.selectNormalChildrenDeptCountById(deptId) > 0) {
            return RestfulResult.error("该部门包含未停用的子部门！");
        }
        return toAjax(deptService.updateDept(dept));
    }

    /**
     * 删除
     */
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @RequiresPermissions("system:dept:remove")
    @GetMapping("/remove/{deptId}")
    @ResponseBody
    public RestfulResult remove(@PathVariable("deptId") Long deptId) {
        if (deptService.selectDeptCount(deptId) > 0) {
            return RestfulResult.warn("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return RestfulResult.warn("部门存在用户,不允许删除");
        }
        deptService.checkDeptDataScope(deptId);
        return toAjax(deptService.deleteDeptById(deptId));
    }

    /**
     * 校验部门名称
     */
    @PostMapping("/checkDeptNameUnique")
    @ResponseBody
    public String checkDeptNameUnique(SysDept dept) {
        return deptService.checkDeptNameUnique(dept);
    }

    /**
     * 加载所有部门列表树（带人数）
     */
    @GetMapping("/selectDeptTreeWithCount")
    @ResponseBody
    public List<Ztree> selectDeptTreeWithCount(SysDept dept) {
        List<Ztree> ztrees = deptService.selectDeptTreeWithCount(dept);
        return ztrees;
    }

    /**
     * 加载所有部门列表树（直属下级）
     */
    @GetMapping("/deptTreeDataImmediateChild")
    @ResponseBody
    public List<Ztree> deptTreeDataImmediateChild(SysDept dept) {
        SysUser user = getSysUser();
        List<Ztree> ztrees = deptService.deptTreeDataImmediateChild(user, dept);
        return ztrees;
    }

    /**
     * 选择菜单树
     */
    @GetMapping("/selectDeptTree/{deptId}")
    public String selectMenuTree(@PathVariable("deptId") Long deptId, ModelMap mmap) {
        mmap.put("sysDept", deptService.selectDeptById(deptId));
        return prefix + "/tree";
    }

    /**
     * 加载角色部门（数据权限）列表树
     */
    @GetMapping("/roleDeptTreeData")
    @ResponseBody
    public List<Ztree> deptTreeData(SysRole role) {
        List<Ztree> ztrees = deptService.roleDeptTreeData(role);
        return ztrees;
    }

}
